<template>
  <div class="asset-transfer-container">
    <h2>资产流转报表</h2>
    
    <div class="filter-bar">
      <el-date-picker v-model="filterFrom.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" default-value="[new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), new Date()]" @change="handleDateChange"/>
      <el-select v-model="filterFrom.transferType" placeholder="选择流转类型">
        <el-option label="全部类型" value="" />
        <el-option label="新增" value="新增" />
        <el-option label="转移" value="转移" />
        <el-option label="借用" value="借用" />
        <el-option label="归还" value="归还" />
        <el-option label="报废" value="报废" />
      </el-select>
      <el-select v-model="filterFrom.deptFilter" placeholder="选择部门">
        <el-option label="全部部门" value="" />
        <el-option label="技术部" value="技术部" />
        <el-option label="市场部" value="市场部" />
        <el-option label="行政部" value="行政部" />
        <el-option label="财务部" value="财务部" />
      </el-select>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
      <el-button type="success" @click="exportReport">导出报表</el-button>
    </div>
    
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>流转类型统计</span>
          </div>
        </template>
        <div id="transferTypeChart" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>月度流转趋势</span>
          </div>
        </template>
        <div id="transferTrendChart" class="chart"></div>
      </el-card>
    </div>
    
    <div class="transfer-records">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>流转记录明细</span>
            <span class="record-count">共 {{ transferRecords.length }} 条记录</span>
          </div>
        </template>
        <el-table :data="transferRecords" style="width: 100%" stripe border>
          <el-table-column prop="transferId" label="流转ID" width="120" />
          <el-table-column prop="assetCode" label="资产编号" width="150" />
          <el-table-column prop="assetName" label="资产名称" min-width="180" />
          <el-table-column prop="transferType" label="流转类型" width="100" />
          <el-table-column prop="fromDept" label="转出部门" width="120" />
          <el-table-column prop="toDept" label="转入部门" width="120" />
          <el-table-column prop="operator" label="操作人" width="100" />
          <el-table-column prop="transferDate" label="流转日期" width="150" />
          <el-table-column prop="remark" label="备注" min-width="200" />
        </el-table>
        <div class="pagination-container">
          <el-pagination 
          v-model:current-page="currentPage" v-model:page-size="pageSize" 
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" 
          :total="totalRecords" @size-change="handleSizeChange"@current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import  {selectassetInfoAPI } from '@/api/asset.js';

//定义报表筛选数据
const filterForm = ref({
  dateRange: [
    new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1),
    new Date()
  ],
  transferType: '', // 默认选中“全部类型”
  deptFilter: ''    // 默认选中“全部部门”
})

//定义列表数据
let transferRecords = ref([])
//加载列表数据
const loadTransferRecords = async () =>{ 
    let resp = await selectassetInfoAPI({
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        dateRange: filterForm.dateRange,
        transferType: filterForm.transferType,
        deptFilter: filterForm.deptFilter
    })
    if (resp.code == 2000) {
        console.log(resp);
        
        transferRecords.value = resp.data.rows
        total.value = resp.data.total
    } else { 
        ElMessage.error(resp.message)
        transferRecords.value = []
        total.value = 0
    }
}
loadTransferRecords()

//点击刷新按钮
const refreshData = () =>{
  loadTransferRecords()
  refreshChart()
}


//定义图标数据
const typeChart = ref(null)
const trendChart= ref(null)


// 统一初始化所有图表
const initCharts = () => {
  initTransferTypeChart() // 饼图
  initTransferTrendChart() // 趋势图
}


//加载所有资产数据
const loadAllData = async () => {
  try {
    const res = await selectAllAssetInfoAPI() 
    // 假设后端返回格式：{ code: 200, data: [...] }，data 是流转记录数组
    if (res.code === 200 && res.data.length > 0) {
      chartData.value = res.data
      initCharts() // 数据加载完成后初始化图表
      ElMessage.success('数据加载成功')
    } else {
      chartData.value = []
      transferTypeChart.value && transferTypeChart.value.setOption({ series: [{ data: [] }] })
      ElMessage.warning('暂无资产流转数据')
    }
  } catch (error) {
    console.error('查询所有资产数据失败：', error)
    transferRecords.value = []
    ElMessage.error('数据加载失败，请重试')
  }
}

// 统计饼图所需数据
const getTypeChartData = () => {
  // 统计各流转类型的数量
  const typeCount = chartData.value.reduce((acc, record) => {
    const { transferType } = record
    acc[transferType] = (acc[transferType] || 0) + 1
    return acc
  }, {})

  // 3. 转换为 ECharts 饼图所需格式
  return Object.entries(typeCount).map(([name, value]) => ({ name, value }))
}

//饼图初始化与更新
const initTransferTypeChart = () => {
  const chartDom = document.getElementById('transferTypeChart')
  if (!chartDom) return

  // 销毁旧实例，避免内存泄漏
  if (typeChart.value) {
    typeChart.value.dispose()
  }

  // 初始化图表实例
  typeChart.value = echarts.init(chartDom)

  // 图表配置项（数据来自动态统计）
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '流转类型',
        type: 'pie',
        radius: '50%',
        data: getTypeChartData(), // 统计的数据
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        // 无数据时显示提示
        label: {
          show: true,
          formatter: () => transferRecords.value.length === 0 ? '暂无数据' : '{b}: {c} ({d}%)'
        }
      }
    ]
  }

  typeChart.value.setOption(option)
}

//按时间统计个流转类型数据
const getTrendChartData = () => {
  // 1. 先根据筛选条件过滤数据
  const filteredData = transferRecords.value.filter(record => {
    const recordDate = new Date(record.transferDate)
    const startDate = new Date(filterForm.value.dateRange[0])
    const endDate = new Date(filterForm.value.dateRange[1])
    const dateMatch = recordDate >= startDate && recordDate <= endDate

    const typeMatch = filterForm.value.transferType ? record.transferType === filterForm.value.transferType : true

    const deptMatch = filterForm.value.deptFilter 
      ? record.fromDept === filterForm.value.deptFilter || record.toDept === filterForm.value.deptFilter 
      : true

    return dateMatch && typeMatch && deptMatch
  })

  // 2. 按“月份”分组统计各类型数量
  const monthData = {} // 格式：{ '2024-09': { 新增: 5, 转移: 3, ... }, ... }
  
  filteredData.forEach(record => {
    const date = new Date(record.transferDate)
    const year = date.getFullYear()
    const month = date.getMonth() + 1 // 月份从0开始，+1转为实际月份
    const monthKey = `${year}-${month.toString().padStart(2, '0')}` // 格式：2024-09

    // 初始化当月数据（若不存在）
    if (!monthData[monthKey]) {
      monthData[monthKey] = { 新增: 0, 转移: 0, 借用: 0, 归还: 0, 报废: 0 }
    }

    // 累加对应类型的数量
    monthData[monthKey][record.transferType]++
  })

  // 3. 转换为折线图所需格式
  const sortedMonths = Object.keys(monthData).sort() // 按月份排序（确保时间顺序正确）
  const types = ['新增', '转移', '借用', '归还', '报废']

  return {
    xAxisData: sortedMonths.map(month => {
      // 格式化x轴显示（如 2024-09 → 9月）
      const [, m] = month.split('-')
      return `${parseInt(m)}月`
    }),
    seriesData: types.map(type => ({
      name: type,
      type: 'line',
      data: sortedMonths.map(month => monthData[month][type])
    }))
  }
}

//趋势图初始化方法
const initTransferTrendChart = () => {
  const chartDom = document.getElementById('transferTrendChart')
  if (!chartDom) return

  // 销毁旧实例，避免内存泄漏
  if (trendChart.value) {
    trendChart.value.dispose()
  }

  // 初始化图表实例
  trendChart.value = echarts.init(chartDom)

  // 获取动态数据
  const { xAxisData, seriesData } = getTrendChartData()

  // 图表配置项（基于后端数据动态生成）
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b} <br/>{a}: {c}' // 自定义提示：月份 + 类型 + 数量
    },
    legend: {
      data: ['新增', '转移', '借用', '归还', '报废'],
      top: 0 // 图例居顶，节省空间
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData.length > 0 ? xAxisData : ['暂无数据'], // 无数据时显示提示
      axisLabel: {
        rotate: 30 // 月份标签旋转30度，避免重叠
      }
    },
    yAxis: {
      type: 'value',
      min: 0, // y轴从0开始，避免数据失真
      axisLabel: {
        formatter: '{value}' // 显示整数
      }
    },
    series: seriesData.length > 0 ? seriesData : [
      // 无数据时显示空系列（避免图表报错）
      { name: '新增', type: 'line', data: [] },
      { name: '转移', type: 'line', data: [] },
      { name: '借用', type: 'line', data: [] },
      { name: '归还', type: 'line', data: [] },
      { name: '报废', type: 'line', data: [] }
    ],
    // 无数据时显示中间提示
    graphic: xAxisData.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: {
        text: '暂无符合条件的数据',
        fontSize: 14,
        fill: '#999'
      }
    }] : []
  }

  trendChart.value.setOption(option)
}


//定义分页参数和方法
let currentPage = ref(1)
let pageSize = ref(5)
let total = ref(0)
const handleSizeChange = () => {
    loadTableData()
}
const handleCurrentChange = () => {
    loadTableData()
}

// 筛选条件变化时，同步更新所有图表
const refreshChart = () => {
  // 优化：仅更新数据，不重新初始化（性能更优）
  trendChart.value && trendChart.value.setOption({
    xAxis: { data: getTrendChartData().xAxisData },
    series: getTrendChartData().seriesData
  })
}

// 窗口大小变化时，所有图表自适应
const handleResize = () => {
  typeChart.value && typeChart.value.resize()
  trendChart.value && trendChart.value.resize()
}

// 组件挂载时加载数据并初始化图表
onMounted(() => {
  loadAllData().then(() => {
    initCharts() // 数据加载完成后初始化所有图表
  })
  window.addEventListener('resize', handleResize)
})

// 组件卸载时销毁所有图表
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  typeChart.value && typeChart.value.dispose()
  trendChart.value && trendChart.value.dispose()
})
</script>

<style scoped>
.asset-transfer-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-count {
  color: #606266;
  font-size: 14px;
}

.chart {
  width: 100%;
  height: 320px;
}

.transfer-records {
  margin-top: 30px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>